package com.sengled.cloud.biz.union.mgt.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.sengled.cloud.biz.union.mgt.common.util.CurrentUserUtil;
import com.sengled.cloud.biz.union.mgt.common.util.Md5Util;
import com.sengled.cloud.biz.union.mgt.common.util.SessionUtil;
import com.sengled.cloud.biz.union.mgt.model.dto.UnionUser;
import com.sengled.cloud.biz.union.mgt.model.po.Shop;
import com.sengled.cloud.biz.union.mgt.model.po.ShopAccount;
import com.sengled.cloud.biz.union.mgt.model.po.User;
import com.sengled.cloud.biz.union.mgt.model.po.UserAccountDetail;
import com.sengled.cloud.biz.union.mgt.model.request.SaveAccountPwdRequest;
import com.sengled.cloud.biz.union.mgt.model.request.SaveAccountStartStopRequest;
import com.sengled.cloud.biz.union.mgt.model.request.SaveShopRequest;
import com.sengled.cloud.biz.union.mgt.model.request.SaveUserAccountRequest;
import com.sengled.cloud.biz.union.mgt.model.request.SaveUserRequest;
import com.sengled.cloud.biz.union.mgt.model.request.SetAccountStatusRequest;
import com.sengled.cloud.biz.union.mgt.model.request.ShopAccountListRequest;
import com.sengled.cloud.biz.union.mgt.model.request.UserAccountListRequest;
import com.sengled.cloud.biz.union.mgt.model.request.UserListQueryRequest;
import com.sengled.cloud.biz.union.mgt.model.response.ResponseMessage;
import com.sengled.cloud.biz.union.mgt.model.vo.SelectBoxDataVo;
import com.sengled.cloud.biz.union.mgt.model.vo.ShopDetailVo;
import com.sengled.cloud.biz.union.mgt.model.vo.ShopQueryParamsBean;
import com.sengled.cloud.biz.union.mgt.model.vo.ShopVo;
import com.sengled.cloud.biz.union.mgt.model.vo.UserAccountsVo;
import com.sengled.cloud.biz.union.mgt.model.vo.UserDetailVo;
import com.sengled.cloud.biz.union.mgt.model.vo.UserVo;
import com.sengled.cloud.biz.union.mgt.service.sys.IUserService;
import com.sengled.cloud.biz.union.mgt.service.sys.impl.AccountService;
import com.sengled.cloud.biz.union.mgt.service.sys.impl.ShopService;
import com.sengled.cloud.biz.union.mgt.service.sys.impl.UserService;

import io.swagger.annotations.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.session.ExpiringSession;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by FMC on 2017/10/27.
 */
@RestController
@RequestMapping("/api/v1")
public class AccountController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AccountService accountService;

    @Resource
    private FindByIndexNameSessionRepository<ExpiringSession> sessionRepository;
    
    @Autowired
    UserService userService;

    
    @ApiOperation(value = "获取账户管理人员列表", notes = "获取账户管理人员列表", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "accountName", value = "账户名", dataType = "String", paramType = "query", defaultValue = "zs"),
            @ApiImplicitParam(name = "userName", value = "用户名", dataType = "String", paramType = "query", defaultValue = "张三"),
            @ApiImplicitParam(name = "accountStatus", value = "账户状态", dataType = "Long", paramType = "query",defaultValue ="1"),
            @ApiImplicitParam(name = "pageNo", value = "当前页码", dataType = "Long", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "显示条数", dataType = "Long", paramType = "query", defaultValue = "30")
    })
    
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/", method = RequestMethod.GET)
    public ResponseMessage<List<UserAccountsVo>> getUserAccounts(@ApiParam(name = "accountName", required = true) String accountName,
                                                      @ApiParam(name = "userName", required = true) String userName,
                                                      @ApiParam(name = "accountStatus", required = true) Integer accountStatus,
                                                      @ApiParam(name = "pageNo") Integer pageNo,
                                                      @ApiParam(name = "pageSize") Integer pageSize,HttpServletRequest request) {
    	UserAccountListRequest query = new UserAccountListRequest();
        query.setPageNo(pageNo);
        query.setPageSize(pageSize);
        query.setAccountName(accountName);
        query.setAccountStatus(accountStatus);
        query.setUserName(userName);
        Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        Long companyId = accountService.getCompanyId(customerId);
        query.setCompanyId(companyId);
        query.setUserId(customerId);
        return accountService.listUserAccountsByPage(query);
    }

    @ApiOperation(value = "所属人员下拉列表（编辑及新增页面）", notes = "所属人员下拉列表（编辑及新增页面）", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/users/", method = RequestMethod.GET)
    public ResponseMessage<List<SelectBoxDataVo>> getUsers(HttpServletRequest request) {
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return accountService.getUsers(customerId);
    }
    
    @ApiOperation(value = "所属权限下拉列表（编辑及新增页面）", notes = "所属权限下拉列表（编辑及新增页面）", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/roles/", method = RequestMethod.GET)
    public ResponseMessage<List<SelectBoxDataVo>> getRoles(HttpServletRequest request) {
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return accountService.getRoles(customerId);
    }
    
    
    @ApiOperation(value = "店铺权限设置checkbox（编辑及新增）", notes = "店铺权限设置checkbox（编辑及新增）", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/shopPermissions/", method = RequestMethod.GET)
    public ResponseMessage<List<ShopAccount>> getShopPermissions(HttpServletRequest request) {

    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return accountService.getShopPermissions(customerId);
    }
 

    
    @ApiOperation(value = "查看人员账户", notes = "查看人员", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "id", value = "人员id", dataType = "Long", paramType = "path", required = true)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    
    @RequestMapping(value = "/userAccounts/{id}", method = RequestMethod.GET)
    public ResponseMessage<UserAccountDetail> getById(@ApiParam(name = "id", required = true) @PathVariable Long id,HttpServletRequest request) {
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return accountService.getUserAccountDetailById(id,customerId);
    }
    
    @ApiOperation(value = "编辑查询（进入人员账户编辑页面初始化接口）", notes = "编辑查询（进入人员账户编辑页面初始化接口）", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "id", value = "人员id", dataType = "Long", paramType = "path", required = true)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    
    @RequestMapping(value = "/userAccounts/edit/{id}", method = RequestMethod.GET)
    public ResponseMessage<UserAccountDetail> getEditPageById(@ApiParam(name = "id", required = true) @PathVariable Long id,HttpServletRequest request) {
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return accountService.getUserAccountDetailById(id,customerId);
    }
    
    @ApiOperation(value = "新增账户管理人员保存", notes = "新增账户管理人员保存接口", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/", method = RequestMethod.POST)
    public ResponseMessage createMessage(@RequestBody SaveUserAccountRequest saveUserAccountRequest,HttpServletRequest request) {
    	saveUserAccountRequest.setId(null);
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return accountService.saveOrUpdateUserAccount(saveUserAccountRequest,customerId);
    }

    @ApiOperation(value = "编辑账户管理人员保存", notes = "编辑账户管理人员保存", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/{id}", method = RequestMethod.PUT)
    public ResponseMessage putUserAccounts(@ApiParam(value = "人员ID", required = true) @PathVariable Long id, @RequestBody SaveUserAccountRequest saveUserAccountRequest,HttpServletRequest request) {
    	saveUserAccountRequest.setId(id);
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
    	ResponseMessage responseMessage = accountService.saveOrUpdateUserAccount(saveUserAccountRequest,customerId);
		try {
			kickAccount(saveUserAccountRequest.getAccountName());
		} catch (Exception e) {
			responseMessage.buildSystemErrorMessage();
			return responseMessage;
		}
        return responseMessage;
    }


    @ApiOperation(value = "删除账户管理人员", notes = "删除账户管理人员", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/{id}", method = RequestMethod.DELETE)
    public ResponseMessage deleteUser(@ApiParam(value = "账号ID", required = true) @PathVariable Long id,HttpServletRequest request) {
    	String userName = accountService.getUserAccountNameById(id);
    	Long currentUserId = CurrentUserUtil.getCurrentAccountId(request);
    	ResponseMessage responseMessage =  accountService.deleteUserAccount(id,currentUserId);
    	try{
    	    kickAccount(userName);
    	}catch(Exception e){
    		responseMessage.buildSystemErrorMessage();
    		return responseMessage;
    	}
        return responseMessage;
    }
    
    @ApiOperation(value = "重置密码", notes = "重置密码", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/pwd/{id}", method = RequestMethod.PUT)
    public ResponseMessage resetPwd(@ApiParam(value = "人员ID", required = true) @PathVariable Long id, @RequestBody SaveAccountPwdRequest saveAccountPwdRequest) {
    	saveAccountPwdRequest.setId(id);
    	
        return accountService.updateUserAccountPwd(saveAccountPwdRequest);
    }
    
    @ApiOperation(value = "用户账号启用停用功能", notes = "用户账号启用停用功能", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/userAccounts/account/{id}", method = RequestMethod.PUT)
    public ResponseMessage startOrStopAccount(@ApiParam(value = "人员ID", required = true) @PathVariable Long id, @RequestBody SaveAccountStartStopRequest saveAccountStartStopRequest) {
    	saveAccountStartStopRequest.setId(id);
        return accountService.updateAccountStartStop(saveAccountStartStopRequest);
    }
    
    public void kickAccount(String userName){
        SessionUtil.invalidateSession(sessionRepository,userName);
    }
    
    public void setAccountStatus(Long id,String accountName,Integer status){
    	SetAccountStatusRequest setAccountStatusRequest = new SetAccountStatusRequest();
    	setAccountStatusRequest.setId(id);
    	setAccountStatusRequest.setAccountStatus(status);
    	accountService.setAccountStatusById(setAccountStatusRequest);
    	
    }
    
    @RequestMapping(value = "/userAccounts/role/{userId}", method = RequestMethod.GET)
    public ResponseMessage<Long> getUserRoleId(@ApiParam(name = "userId", required = true) @PathVariable Long userId,HttpServletRequest request) {
    	
        return accountService.getUserRoleId(userId);
    }
}
